<template>
    <div class="d-main">
        <div class="mv">
            <div class="header">
                <h3>本页面只做下载（TESTING）</h3>
                <p>下载路径： {{downloadPath}} </p>
                <el-button type="primary" @click="chooseDir">修改路径</el-button>
            </div>
            <el-form :inline="true" class="search">
                <el-input v-model="keyword" placeholder="请输入内容"></el-input>
                <el-button type="primary" @click="search">搜&emsp;索</el-button>
                <el-button type="primary" @click="download">下&emsp;载</el-button>
            </el-form>
            <div class="video-list">
                <div class="video-item" v-for="item in videoInfoList" :key="item.id" :class="{active: videoIds.indexOf(item.id) != -1}">
                    <label>
                        <input type="checkbox" :value="item.id" v-model="videoIds">
                        <div class="title" v-html="item.hltitle + item.id"></div>
                        <img :src="item.headImg" alt="">
                    </label>
                </div>
            </div>
        </div>
        <div class="download-list">
            <h4>正在下载</h4>
            <div v-for="item in downloadList" :key="item.id">
                <p>{{item.title}}</p>
                <p>{{item.fileSize}}</p>
                <p>{{item.downloadSize}}</p>
            </div>
        </div>
    </div>
</template>
<script>
import path from 'path';
import fs from 'fs';
import request from 'request';
import electron from 'electron';
const dialog = electron.remote.dialog;

export default {
    name: 'main',
    data() {
        return {
            keyword: 't-ara',
            videoInfoList: [],
            videoMap: {},
            videoIds: [],
            versions: process.versions,
            loading: true,
            videoInfo: {url: ''},
            isShowVideo: false,
            downloadList: [],
            downloadPath: process.cwd() + '/mv'
        };
    },
    mounted() {
        this.init();
    },
    methods: {
        init() {
            this.search();
        },
        search() {
            let me = this;
            $.ajax({
                url: 'http://soapi.yinyuetai.com/search/video-search',
                type: 'GET',
                dataType: 'jsonp',
                data: {
                    keyword: this.keyword,
                    pageIndex: 1,
                    pageSize: 24,
                    offset: 0,
                    orderType: '',
                    area: '',
                    property: '',
                    durationStart: 0,
                    durationEnd: '',
                    regdateStart: '',
                    regdateEnd: 1497690299,
                    clarityGrade: '',
                    source: '3,10',
                    thirdSource: '17,57'
                },
                success(res) {
                    me.videoInfoList = res.videos.data;
                    me.initVideoInfoMap();
                }
            });
        },
        handleClose(done) {
            this.$refs.iVideo.pause();
            done();
        },
        initVideoInfoMap() {
            let tmp = {};
            this.videoInfoList.forEach(item => {
                tmp[item.id] = item;
            });
            this.videoMap = tmp;
        },
        // 获取最高分辨率的URL
        getHighestDefinitionUrl(res) {
            // 清晰度 超清 高清 标清
            let definitionMap = ['heVideoUrl', 'hdVideoUrl', 'hcVideoUrl'];
            let url = '';
            definitionMap.some(definition => {
                if (res[definition]) {
                    url = res[definition];
                    return true;
                }
            });
            return url;
        },
        downloadByHttp(videoInfo) {
            let destWriter = fs.createWriteStream(videoInfo.dest);
            request(videoInfo.url).on('error', err => {
                console.log(err);
            }).on('response', res => {
                videoInfo.fileSize = res.headers['content-length'];
            }).on('data', chunk => {
                videoInfo.downloadSize += chunk.length;
            }).on('end', () => {
                console.log('end');
            }).pipe(destWriter);
        },
        download() {
            this.videoIds.forEach(id => {
                let url = 'http://www.yinyuetai.com/api/info/get-video-urls?json=true&videoId=';
                $.ajax({
                    url: url + id
                }).then(res => {
                    let videoInfo = $.extend(true, {fileSize: 0, downloadSize: 0}, this.videoMap[id]);
                    let url = this.getHighestDefinitionUrl(res);
                    let dest = path.resolve(this.downloadPath, (videoInfo.hltitle.replace(/\//g, '')) + '.mp4');
                    videoInfo.url = url;
                    videoInfo.dest = dest;
                    this.downloadList.push(videoInfo);
                    this.downloadByHttp(videoInfo);
                });
            });
        },
        chooseDir() {
            dialog.showOpenDialog({properties: ['openDirectory']}, dirs => {
                this.downloadPath = dirs[0];
            });
        }
    }
};
</script>
<style lang="less">
.d-main {
    display: flex;
    .mv {
        flex: 1;
    }
    .download-list {
        width: 400px;
        height: 100%;
    }
    .header {
        overflow: hidden;
        h3 {
            text-align: center;
            margin: 0;
            padding: 15px;
        }
        .el-button {
            position: absolute;
            right: 11px;
            top: 14px;
            color: #545454;
        }
    }

    .search {
        margin-bottom: 20px;
    }

    .video-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
        text-align: center;
    }

    .video-item {
        width: 240px;
        cursor: pointer;
        border: 1px solid #ccc;
        margin-bottom: 20px;
        label {
            display: block;
        }
        &.active {
            border-color: red;
        }
        .title {
            box-sizing: border-box;
            width: 100%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            padding: 10px 20px;
        }
        img {
            width: 100%;
            vertical-align: bottom;
            border-top: 1px solid #ccc;
        }
        input[type="checkbox"] {
            display: none;
        }
    }

    .el-form {
        text-align: center;
    }

    .el-input,
    .el-input__inner {
        width: initial;
    }
}
</style>
